<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="投保人名称" prop="toubaoId">
        <el-select v-model="queryParams.toubaoId" placeholder="请选择投保人名称" clearable>
          <el-option
              v-for="dict in taobaoList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="被保险人名称" prop="beibaoId">
        <el-select v-model="queryParams.beibaoId" placeholder="请选择被保险人名称" clearable>
          <el-option
              v-for="dict in taobaoList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="保险人名称" prop="baoxianId">
        <el-select v-model="queryParams.baoxianId" placeholder="请选择保险人名称" clearable>
          <el-option
              v-for="dict in baoxianList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="经纪/代理公司名称" prop="proxyId" label-width="130px">
        <el-select v-model="queryParams.proxyId" placeholder="请选择经纪/代理公司名称" clearable>
          <el-option
              v-for="dict in proxyList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="险种" prop="insureType" label-width="50">
        <el-select v-model="queryParams.insureType" placeholder="险种" clearable>
          <el-option
              v-for="dict in dict.type.insure_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['insurance:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="合同名称" align="center" prop="contractName"/>
      <el-table-column label="保单号码" align="center" prop="insureNo"/>
      <el-table-column label="标的内容" align="center" prop="targetContent"/>
      <el-table-column label="经纪/代理公司" align="center" prop="proxyName"/>
      <el-table-column label="经纪/代理佣金比例(%)" align="center" prop="commissionRate"/>
      <el-table-column label="经纪/代理佣金(元)" align="center" prop="commission"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
              v-if="!scope.row.id"
              type="text"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd(scope.row)"
              v-hasPermi="['insurance:contract:add']"
          >新增合同
          </el-button>
          <el-button
              v-else
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['insurance:contract:edit']"
          >修改合同
          </el-button>
          <el-button
              v-if="scope.row.id"
              size="mini"
              type="text"
              @click="goToPremiumPlan(scope.row,'/views/insurance/premiumPlan/index')"
              v-hasPermi="['insurance:plan:query']"
          >保费缴纳信息
          </el-button>
          <el-button
              v-if="scope.row.id"
              size="mini"
              type="text"
              @click="goToPremiumPlan(scope.row,'/views/commission/plan/index')"
              v-hasPermi="['commission:plan:query']"
          >经纪/代理佣金支付信息
          </el-button>
          <el-button
              v-if="scope.row.id"
              size="mini"
              type="text"
              @click="goToPremiumPlan(scope.row,'/views/insurance/coinsurance/index')"
              v-hasPermi="['insurance:coinsurance:query']"
          >共保信息
          </el-button>
          <el-button
              style="color: red"
              v-if="scope.row.id"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['insurance:contract:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改保险合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="标的地址" prop="targetAddress">
          <el-input v-model="form.targetAddress" placeholder="请输入标的地址">
            <template slot="append">
              <el-button slot="append" @click="openMap"> 地图</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="经纪/代理佣金" prop="commission">
          <el-input v-model="form.commission" placeholder="请输入经纪/代理佣金">
            <template slot="append">
              <el-button slot="append">元</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="经纪/代理佣金比例" prop="commissionRate">
          <el-input v-model="form.commissionRate" placeholder="请输入经纪/代理佣金比例">
            <template slot="append">
              <el-button slot="append">%</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="标的内容">
          <el-input v-model="form.targetContent" type="textarea" :rows=2 placeholder="请输入标的内容"/>
        </el-form-item>
        <!--<el-row>-->
        <!--  <el-col :span="12">-->
        <!--    <el-form-item label="标的地址" prop="targetAddress">-->
        <!--     -->
        <!--    </el-form-item>-->
        <!--    &lt;!&ndash;<el-form-item label="标的经度" prop="longitude">&ndash;&gt;-->
        <!--    &lt;!&ndash;  <el-input v-model="form.longitude" placeholder="请输入标的经度" />&ndash;&gt;-->
        <!--    &lt;!&ndash;</el-form-item>&ndash;&gt;-->
        <!--    &lt;!&ndash;<el-form-item label="标的纬度" prop="latitude">&ndash;&gt;-->
        <!--    &lt;!&ndash;  <el-input v-model="form.latitude" placeholder="请输入标的纬度" />&ndash;&gt;-->
        <!--    &lt;!&ndash;</el-form-item>&ndash;&gt;-->
        <!--  </el-col>-->
        <!--  <el-col :span="12">-->
        <!--   -->
        <!--  </el-col>-->
        <!--</el-row>-->
        <!--<el-row>-->
        <!--  &lt;!&ndash;<el-col :span="12">&ndash;&gt;-->
        <!--  &lt;!&ndash;  <el-form-item label="经纪/代理公司" prop="proxyName">&ndash;&gt;-->
        <!--  &lt;!&ndash;    <el-input v-model="form.proxyName" placeholder="请输入经纪/代理公司" readonly/>&ndash;&gt;-->
        <!--  &lt;!&ndash;  </el-form-item>&ndash;&gt;-->
        <!--  &lt;!&ndash;</el-col>&ndash;&gt;-->
        <!--  <el-col :span="24">-->

        <!--  </el-col>-->
        <!--</el-row>-->
        <!--<el-row>-->
        <!--  <el-col :span="24">-->
        <!--   -->
        <!--  </el-col>-->
        <!--</el-row>-->
        <!--&lt;!&ndash;<el-row>&ndash;&gt;-->
        <!--&lt;!&ndash;  <el-col :span="24">&ndash;&gt;-->
        <!--&lt;!&ndash;    <el-form-item label="经纪/代理佣金支付证明上传" prop="fileIds">&ndash;&gt;-->
        <!--&lt;!&ndash;      <file-upload v-model="form.fileIds" :fileType="['pdf']" :fileSize="99999" :limit="99999"/>&ndash;&gt;-->
        <!--&lt;!&ndash;    </el-form-item>&ndash;&gt;-->
        <!--&lt;!&ndash;  </el-col>&ndash;&gt;-->
        <!--&lt;!&ndash;</el-row>&ndash;&gt;-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="选取区域"
        :visible.sync="areaShow"
        width="1000px"
        append-to-body
    >
      <drawLineOLWindow
          v-if="areaShow"
          @coordinate="coordinate"
          class="pointChoose"
          :defaultCoord="targetAddress"
      />
      <el-button type="primary" @click="savePoint" style="margin-top: 5px"
      >确定
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
import {listContract, getContract, delContract, addContract, updateContract} from "@/api/insurance/contract";
import {isEmpty, isValidAmount, isValidDecimal} from "@/utils/validate";
import {getBaoxianlist, getDaililist, getFengkonglist, getToubaolist} from "@/api/common/common";
import drawLineOLWindow from "@/components/OpenLayersWindow/choosePointOLWindow/index.vue";

export default {
  name: "Contract",
  components: {drawLineOLWindow},
  dicts: ['insure_type'],
  data() {
    const checkCommission = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (!isValidAmount(value)) {
        callback(new Error('请输入正确的金额'));
        return;
      }
      callback();
    }
    const checkCommissionRate = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback();
        return
      }
      if (value > 100) {
        callback(new Error('经纪/代理佣金比例不能大于100'));
        return;
      }
      if (value < 0) {
        callback(new Error('经纪/代理佣金比例不能小于0'));
        return;
      }
      if (!isValidDecimal(value)) {
        callback(new Error('请输入正确的经纪/代理佣金比例，小数不能超过2位'));
        return;
      }
      callback();
    }
    return {
      targetAddress:null,
      areaShow: false,
      baoxianList: [],
      taobaoList: [],
      beibaoList: [],
      proxyList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTbInsuranceContractPremiumPlan: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保险合同表格数据
      contractList: [],
      // 保险合同回款计划表格数据
      tbInsuranceContractPremiumPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        insureId: null,
        targetAddress: null,
        longitude: null,
        latitude: null,
        targetContent: null,
        proxyId: null,
        commissionRate: null,
        commission: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        commission: [
          // {required: true, message: "保险费率不能为空", trigger: "blur"},
          {validator: checkCommission, trigger: 'blur'}
        ],
        commissionRate: [
          {validator: checkCommissionRate, trigger: 'blur'}
        ]
      }
    };
  },
  created() {
    this.initData()
    this.getList();
  },
  methods: {
    savePoint() {
      this.areaShow = false;
    },
    coordinate(val) {
      this.form.targetAddress = val;
    },
    openMap() {
      this.areaShow = true
    },
    /** 查询保险合同列表 */
    getList() {
      this.loading = true;
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        proxyName: null,
        insureId: null,
        targetAddress: null,
        longitude: null,
        latitude: null,
        targetContent: null,
        proxyId: null,
        commissionRate: null,
        commission: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        fileIds: [],
      };
      this.tbInsuranceContractPremiumPlanList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      if (isEmpty(row.insureId)) {
        this.$modal.msgError('缺少保单信息')
        return
      }
      this.reset();
      this.form.proxyName = row.proxyName
      this.form.proxyId = row.proxyId
      this.form.insureId = row.insureId
      this.open = true;
      this.title = "添加保险合同";
    },


    goToPremiumPlan(row, path) {
      this.$router.push(
          {
            path: path,
            query: {
              'insureId': row.insureId,
              'contractId': row.id
            }
          }
      );
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContract(id).then(response => {
        this.form = response.data;
        this.tbInsuranceContractPremiumPlanList = response.data.tbInsuranceContractPremiumPlanList;
        this.open = true;
        this.title = "修改保险合同";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tbInsuranceContractPremiumPlanList = this.tbInsuranceContractPremiumPlanList;
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的保险合同？').then(function () {
        return delContract(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    initData() {
      getToubaolist().then().then(res => {
        this.taobaoList = res.data
      })
      getBaoxianlist().then().then(res => {
        this.baoxianList = res.data
      })
      getDaililist().then().then(res => {
        this.proxyList = res.data
      })
    },
    /** 保险合同回款计划序号 */
    rowTbInsuranceContractPremiumPlanIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 保险合同回款计划添加按钮操作 */
    handleAddTbInsuranceContractPremiumPlan() {
      let obj = {};
      obj.insureId = "";
      obj.planName = "";
      obj.planAmount = "";
      obj.planDate = "";
      obj.rate = "";
      obj.demand = "";
      obj.responsiblePerson = "";
      this.tbInsuranceContractPremiumPlanList.push(obj);
    },
    /** 保险合同回款计划删除按钮操作 */
    handleDeleteTbInsuranceContractPremiumPlan() {
      if (this.checkedTbInsuranceContractPremiumPlan.length == 0) {
        this.$modal.msgError("请先选择要删除的保险合同回款计划数据");
      } else {
        const tbInsuranceContractPremiumPlanList = this.tbInsuranceContractPremiumPlanList;
        const checkedTbInsuranceContractPremiumPlan = this.checkedTbInsuranceContractPremiumPlan;
        this.tbInsuranceContractPremiumPlanList = tbInsuranceContractPremiumPlanList.filter(function (item) {
          return checkedTbInsuranceContractPremiumPlan.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTbInsuranceContractPremiumPlanSelectionChange(selection) {
      this.checkedTbInsuranceContractPremiumPlan = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('insurance/contract/export', {
        ...this.queryParams
      }, `contract_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
.pointChoose {
  height: 670px;
}
</style>
